package com.lcf.app.kkfileview.controller;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author ChenFei
 * @date 2022/10/20
 */
@Controller
public class ViewController {

    private String path = "C:/Users/eryang/Desktop/";

    /**
     * 向前端返回流
     *
     * @param response
     * @param fileName
     * @throws Exception
     */
    @GetMapping("stream")
    public void stream(HttpServletResponse response, String fileName) throws Exception {
        try (
                FileInputStream in = new FileInputStream(path + fileName);
                ServletOutputStream out = response.getOutputStream()
        ) {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            IOUtils.copy(in, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预览地址：http://127.0.0.1:8080/view?fileName=文件名称
     *
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("view")
    public String view(String fileName) throws UnsupportedEncodingException {
        String object = "http://127.0.0.1:8080/stream?fileName=" + fileName;// 需要预览的文件流
        //
        object += "&fullfilename=" + fileName; //TODO 这个比较重要，kkFileView 好像是根据文件后缀进行类型判断的
        return "redirect:http://127.0.0.1:8012/onlinePreview?url=" + URLEncoder.encode(Base64Util.encode(object), "utf-8");
    }

}
